package org.mii.safeguard_v1.security.web;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import net.sf.json.JSONObject;

import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import org.mii.safeguard_v1.base.service.ServiceException;
import org.mii.safeguard_v1.base.web.CrudActionSupport;
import org.mii.safeguard_v1.security.entity.Authority;
import org.mii.safeguard_v1.security.entity.Resource;
import org.mii.safeguard_v1.security.service.AuthorityManager;
import org.mii.safeguard_v1.security.service.AuthorityUtils;
import org.mii.safeguard_v1.security.service.ResourceManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springside.modules.orm.hibernate.HibernateWebUtils;
import org.springside.modules.security.springsecurity.SpringSecurityUtils;
import org.springside.modules.utils.AjaxJQueryUtils;
import org.springside.modules.web.struts2.Struts2Utils;

@SuppressWarnings("serial")
@Results( {
		@Result(name = CrudActionSupport.RELOAD, location = "resc.action", type = "redirect"),
		@Result(name = CrudActionSupport.NOTICE, location = "notice.jsp", type = "redirect"),
		@Result(name = CrudActionSupport.DENY_ACCESS, location = "common/403.jsp", type = "redirect") })
@Namespace("/security")
public class RescAction extends CrudActionSupport<Resource> {

	@Autowired
	ResourceManager resourceManager;

	@Autowired
	AuthorityManager authorityManager;

	// 基本属性
	private Resource entity;
	private Integer id;
	private List<Resource> allRescs;

	private List<Authority> allAuths;

	// 资源相关属性

	@Override
	public String delete() throws Exception {
		try {
			resourceManager.delete(id);
			addActionMessage("删除资源成功");
			SpringSecurityUtils.updateResource(Struts2Utils.getSession()
					.getServletContext());
		} catch (ServiceException e) {
			logger.error(e.getMessage(), e);
			addActionMessage(e.getMessage());
		}
		return RELOAD;
	}

	@Override
	public String list() throws Exception {
		allRescs = resourceManager.getAllDistinct();
		return SUCCESS;
	}

	@Override
	public String input() throws Exception {
		// allRescs = resourceManager.getAll();
		// checkedAuthIds = entity.getAuthIds();
		return INPUT;
	}

	@Override
	protected void prepareModel() throws Exception {
		if (id != null) {
			entity = resourceManager.get(id);
		} else {
			entity = new Resource();
		}
	}

	public void setId(Integer id) {
		this.id = id;
	}

	@Override
	public String save() throws Exception {
		resourceManager.save(entity);
		addActionMessage("保存资源成功");
		SpringSecurityUtils.updateResource(Struts2Utils.getSession()
				.getServletContext());
		return RELOAD;
	}

	public Resource getModel() {
		return entity;
	}

	/**
	 * 
	 * @return 分配权限
	 * @throws Exception
	 */
	public String assignAuth() throws Exception {
		HttpServletRequest request = ServletActionContext.getRequest();
		allAuths = authorityManager.getAll();
		entity = resourceManager.get(Integer.parseInt(request
				.getParameter("id")));
		HibernateWebUtils.bindingAuthorizedResource(allAuths, entity
				.getAuthIds(), Authority.class, "id", "isAuthorized");
		request.setAttribute("rescId", entity.getId());
		request.setAttribute("rescName", entity.getValue());

		return "authority";

	}

	/**
	 * Ajax动态调用授权
	 * 
	 * @return
	 * @throws Exception
	 */
	public String changeAuth() throws Exception {
		HttpServletRequest request = Struts2Utils.getRequest();
		JSONObject jsonObject = AjaxJQueryUtils.readJson(request);
		String rescId = jsonObject.getString("obId");
		String authId = jsonObject.getString("opId");
		boolean ischecked = jsonObject.getInt("check") == 1;
		Resource entity = resourceManager.get(Integer.valueOf(rescId));

		int udt = AuthorityUtils.updateAuthorites(entity.getAuthorities(),
				Integer.valueOf(authId), ischecked, "id", Authority.class);
		// 重新保存
		resourceManager.save(entity);
		SpringSecurityUtils.updateResource(Struts2Utils.getSession()
				.getServletContext());
		AjaxJQueryUtils.print(Struts2Utils.getResponse(), String.valueOf(udt));
		return null;

	}

	public List<Resource> getAllRescs() {
		return allRescs;
	}

	public List<Authority> getAllAuths() {
		return allAuths;
	}

}
